package com.csust.cg.mongodb.service.impl;

import com.csust.cg.mongodb.domain.Result;
import com.csust.cg.mongodb.domain.entity.ConnectGroup;
import com.csust.cg.mongodb.domain.entity.Connect;
import com.csust.cg.mongodb.domain.vo.ConnectionVO;
import com.csust.cg.mongodb.mapper.ConnectGroupMapper;
import com.csust.cg.mongodb.mapper.ConnectMapper;
import com.csust.cg.mongodb.service.SaveConnectService;
import com.csust.cg.mongodb.utils.MongoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author chenguang
 */
@Service
public class SaveConnectServiceImpl implements SaveConnectService {

    @Autowired
    private ConnectMapper connectMapper;

    @Autowired
    private ConnectGroupMapper connectGroupMapper;

    @Override
    public Result getAllSaveConnectList(String userId) {
        List<ConnectGroup> groups;
        try {
            groups = connectGroupMapper.selectGroupListByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误，请联系开发人员！");
        }
        List<Map<String, Object>> result = new ArrayList<>();
        if (groups == null || groups.size() < 1) {
            return Result.success(result);
        }
        for (ConnectGroup group : groups) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("group", group);
            List<Connect> connectionList;
            try {
                connectionList = connectMapper.getConnectListByGroupIdAndUserId(group.getId(), userId);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("系统错误，请联系开发人员！");
            }
            map.put("connectionList", connectionList);
            result.add(map);
        }
        return Result.success(result);
    }

    @Override
    public Result addSaveConnectByGroup(ConnectionVO connection, String userId) {
        for (Integer group : connection.getGroups()) {
            Connect connect = new Connect();
            // 保存
            connect.setType(false);
            connect.setUpdateTime(new Date());
            connect.setUserId(userId);
            connect.setGroupId(group);
            connect.setName(connection.getName());
            connect.setIp(connection.getIp());
            connect.setPort(connection.getPort());
            connect.setProtocol(connection.getProtocol());
            connect.setAuth(connection.getAuth());
            if (connection.getAuth()) {
                connect.setUsername(connection.getUsername());
                connect.setPassword(connection.getPassword());
                connect.setAuthMechanism(connection.getAuthMechanism());
                connect.setAuthDatabase(connection.getAuthDatabase());
            }
            try {
                connectMapper.insertSaveConnect(connect);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("系统保存连接错误，请联系开发人员！");
            }
        }
        return Result.success();
    }

    @Override
    public Integer addSaveConnect(ConnectionVO connection, String userId) {
        Integer group = connection.getGroups().get(0);
        Connect connect = new Connect();
        connect.setType(false);
        connect.setUpdateTime(new Date());
        connect.setUserId(userId);
        connect.setGroupId(group);
        connect.setName(connection.getName());
        connect.setIp(connection.getIp());
        connect.setPort(connection.getPort());
        connect.setProtocol(connection.getProtocol());
        connect.setAuth(connection.getAuth());
        if (connection.getAuth()) {
            connect.setUsername(connection.getUsername());
            connect.setPassword(connection.getPassword());
            connect.setAuthMechanism(connection.getAuthMechanism());
            connect.setAuthDatabase(connection.getAuthDatabase());
        }
        try {
            connectMapper.insertSaveConnect(connect);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return connect.getId();
    }

    @Override
    public Result editSaveConnect(ConnectionVO connection, String userId, Integer id) {
        Connect connect = new Connect();
        connect.setUpdateTime(new Date());
        connect.setId(id);
        connect.setUserId(userId);
        connect.setGroupId(connection.getGroups().get(0));
        connect.setName(connection.getName());
        connect.setIp(connection.getIp());
        connect.setPort(connection.getPort());
        connect.setProtocol(connection.getProtocol());
        connect.setAuth(connection.getAuth());
        if (connection.getAuth()) {
            connect.setUsername(connection.getUsername());
            connect.setPassword(connection.getPassword());
            connect.setAuthMechanism(connection.getAuthMechanism());
            connect.setAuthDatabase(connection.getAuthDatabase());
        }
        try {
            connectMapper.updateSaveConnectByIdAndUserId(connect);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统更新连接错误，请联系开发人员！");
        }
        return Result.success();
    }

    @Override
    public Result removeSaveConnects(String userId, List<Integer> ids) {
        try {
            connectMapper.deleteByUserIdAndIds(userId, ids);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统删除连接错误，请联系开发人员！");
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result importSaveConnectList(List<ConnectionVO> connectionList, String userId) {
        List<ConnectGroup> groups = connectGroupMapper.selectGroupListByUserId(userId);
        Map<String, Integer> groupMap = new HashMap<>(groups.size());
        groups.forEach(group -> groupMap.put(group.getGroupName(), group.getId()));
        try {
            connectionList.forEach(connection -> {
                Connect connect = new Connect();
                connect.setUserId(userId);
                connect.setUpdateTime(new Date());
                String groupName = connection.getGroupName();
                if (!groupMap.containsKey(groupName)) {
                    ConnectGroup group = new ConnectGroup();
                    group.setUserId(userId);
                    group.setGroupName(groupName);
                    group.setCreateTime(new Date());
                    connectGroupMapper.insertGroup(group);
                    groupMap.put(groupName, group.getId());
                }
                connect.setGroupId(groupMap.get(groupName));
                connect.setType(false);
                connect.setName(connection.getName());
                connect.setProtocol(connection.getProtocol());
                connect.setIp(connection.getIp());
                connect.setPort(connection.getPort());
                connect.setAuth(connection.getAuth());
                if (connection.getAuth()) {
                    connect.setUsername(connection.getUsername());
                    connect.setPassword(connection.getPassword());
                    connect.setAuthDatabase(connection.getAuthDatabase());
                    connect.setAuthMechanism(connection.getAuthMechanism());
                }
                connectMapper.insertSaveConnect(connect);
            });
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("系统导入连接信息错误，请联系开发人员！");
        }
        return Result.success();
    }

    @Override
    public Result editSaveConnectNameAndGroup(String connectionId, String name, Integer groupId, String userId, Integer id) {
        try {
            connectMapper.updateSaveConnectNameAndGroupByUserIdAndId(name, groupId, userId, id);
            MongoUtils.getConnection(connectionId).setName(name);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("系统更新连接信息错误，请联系开发人员！");
        }
        return Result.success();
    }
}
